﻿using System;
using System.Windows;
using System.Windows.Controls;
using Hardcodet.Wpf.TaskbarNotification;
using WpfApp1.Core;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Threading;
using System.Linq;
using System.IO;
using Drawing = System.Drawing;
using WPFApplication = System.Windows.Application;
using WPFMessageBox = System.Windows.MessageBox;
using MahApps.Metro.Controls;

namespace WpfApp1
{
    public partial class MainWindow : MetroWindow, IDisposable
    {
        private readonly SyncService _syncService;
        private HistoryWindow? _historyWindow;
        private TaskbarIcon? _notifyIcon;
        private bool _isClosing;
        private bool _isDisposed;
        private bool _isSyncEnabled = true;
        private readonly DispatcherTimer _autoCleanTimer;
        private DateTime _lastCleanTime;
        
        public MainWindow()
        {
            InitializeComponent();
            _syncService = new SyncService();
            _notifyIcon = NotifyIcon;
            InitializeNotifyIcon();
            
            // 先初始化托盘图标为灰色状态
            if (_notifyIcon != null)
            {
                _notifyIcon.Icon = GetGrayIcon();
                _notifyIcon.ToolTipText = "正在加载...";
            }

            // 初始化自动清理定时器
            _autoCleanTimer = new DispatcherTimer();
            _autoCleanTimer.Interval = TimeSpan.FromHours(1); // 每小时检查一次
            _autoCleanTimer.Tick += AutoCleanTimer_Tick;
            _autoCleanTimer.Start();

            // 启动初始化过程
            _ = InitializeAsync();

            // 隐藏主窗口
            WindowState = WindowState.Minimized;
            ShowInTaskbar = false;
            Hide();
        }

        private async Task InitializeAsync()
        {
            try
            {
                // 连接服务器
                UpdateStatus("正在连接服务器...");
                Debug.WriteLine("开始连接服务器...");
                await _syncService.StartAsync();
                Debug.WriteLine("服务器连接成功");

                // 立即加载历史记录
                Debug.WriteLine("开始加载历史记录...");
                UpdateStatus("正在加载历史记录...");
                var history = await _syncService.GetHistoryAsync();
                Debug.WriteLine($"历史记录加载完成，共 {history.Count} 条");

                // 初始化历史记录窗口
                if (_historyWindow == null)
                {
                    Debug.WriteLine("正在创建历史记录窗口...");
                    _historyWindow = new HistoryWindow(_syncService);
                    _historyWindow.UpdateHistory(history);
                    Debug.WriteLine("历史记录窗口已创建并更新");
                }

                // 初始化剪贴板监控
                UpdateStatus("正在初始化剪贴板监控...");
                Debug.WriteLine("开始初始化剪贴板监控...");
                ClipboardMonitor.Start();
                ClipboardMonitor.ContentChanged += OnClipboardChanged;
                Debug.WriteLine("剪贴板监控初始化完成");

                // 更新托盘图标
                if (_notifyIcon != null)
                {
                    _notifyIcon.Icon = new Drawing.Icon(WPFApplication.GetResourceStream(new Uri("pack://application:,,,/Resources/clipboard.ico")).Stream);
                    _notifyIcon.ToolTipText = "剪贴板同步";
                    _notifyIcon.ShowBalloonTip("剪贴板同步", "服务已启动", BalloonIcon.Info);
                }
                
                UpdateStatus("服务已启动");
                Debug.WriteLine("启动完成");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"启动失败: {ex}");
                ShowError($"启动失败: {ex.Message}");
                
                // 更新托盘图标为灰色状态
                if (_notifyIcon != null)
                {
                    _notifyIcon.Icon = GetGrayIcon();
                    _notifyIcon.ToolTipText = "连接失败 - 点击重试";
                    _notifyIcon.DoubleClickCommand = new RelayCommand(async () => await InitializeAsync());
                }
                
                // 不要关闭程序,让用户可以重试
                UpdateStatus("连接失败 - 双击托盘图标重试");
            }
        }

        private Drawing.Icon? GetGrayIcon()
        {
            try
            {
                var iconUri = new Uri("pack://application:,,,/Resources/clipboard.ico");
                var iconStream = WPFApplication.GetResourceStream(iconUri)?.Stream;
                if (iconStream != null)
                {
                    using var icon = new Drawing.Icon(iconStream);
                    using var bitmap = icon.ToBitmap();
                    using var grayBitmap = new Drawing.Bitmap(bitmap.Width, bitmap.Height);
                    using var g = Drawing.Graphics.FromImage(grayBitmap);
                    var colorMatrix = new Drawing.Imaging.ColorMatrix(
                        new float[][]
                        {
                            new float[] {0.3f, 0.3f, 0.3f, 0, 0},
                            new float[] {0.3f, 0.3f, 0.3f, 0, 0},
                            new float[] {0.3f, 0.3f, 0.3f, 0, 0},
                            new float[] {0, 0, 0, 1, 0},
                            new float[] {0, 0, 0, 0, 1}
                        });
                    var attributes = new Drawing.Imaging.ImageAttributes();
                    attributes.SetColorMatrix(colorMatrix);
                    g.DrawImage(bitmap, new Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                        0, 0, bitmap.Width, bitmap.Height,
                        Drawing.GraphicsUnit.Pixel, attributes);
                    var iconHandle = grayBitmap.GetHicon();
                    return Drawing.Icon.FromHandle(iconHandle);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"创建灰色图标失败: {ex.Message}");
            }
            return null;
        }

        private void InitializeNotifyIcon()
        {
            if (_notifyIcon != null)
            {
                _notifyIcon.DoubleClickCommand = new RelayCommand(ShowHistoryWindow);
                
                // 初始化菜单图标
                HistoryMenuItem.Icon = MenuIcons.CreateHistoryIcon();
                
                SyncMenuItem.Icon = MenuIcons.CreateSyncIcon(_isSyncEnabled);
                SyncMenuItem.IsChecked = _isSyncEnabled;
                
                CleanMenuItem.Icon = MenuIcons.CreateCleanIcon();
                
                ExitMenuItem.Icon = MenuIcons.CreateExitIcon();
                
                // 检查并设置开机自启动状态
                var isAutoStartEnabled = IsAutoStartEnabled();
                AutoStartMenuItem.Icon = MenuIcons.CreateAutoStartIcon(isAutoStartEnabled);
                AutoStartMenuItem.IsChecked = isAutoStartEnabled;
            }
        }

        private bool IsAutoStartEnabled()
        {
            try
            {
                var startupPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.Startup),
                    "ClipboardSync.lnk"
                );
                return File.Exists(startupPath);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"检查开机自启动状态失败: {ex}");
                return false;
            }
        }

        private void SetAutoStart(bool enable)
        {
            try
            {
                var startupPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.Startup),
                    "ClipboardSync.lnk"
                );

                if (enable)
                {
                    var exePath = Process.GetCurrentProcess().MainModule?.FileName;
                    if (exePath != null)
                    {
                        var workingDirectory = AppDomain.CurrentDomain.BaseDirectory;
                        
                        // 创建快捷方式
                        using (StreamWriter writer = new StreamWriter(startupPath))
                        {
                            string shortcutContent = $@"[InternetShortcut]
URL=file:///{exePath.Replace('\\', '/')}
IconIndex=0
HotKey=0
IDList=
IconFile={exePath.Replace('\\', '/')}
[{{000214A0-0000-0000-C000-000000000046}}]
Prop3=19,0";
                            writer.Write(shortcutContent);
                        }
                    }
                }
                else if (File.Exists(startupPath))
                {
                    File.Delete(startupPath);
                }

                // 更新图标
                if (AutoStartMenuItem != null)
                {
                    AutoStartMenuItem.Icon = MenuIcons.CreateAutoStartIcon(enable);
                }
            }
            catch (Exception ex)
            {
                WPFMessageBox.Show($"设置开机自启动失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void AutoStartMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            if (menuItem != null)
            {
                menuItem.IsChecked = !menuItem.IsChecked;
                SetAutoStart(menuItem.IsChecked);
            }
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // 连接服务器
                UpdateStatus("正在连接服务器...");
                Debug.WriteLine("开始连接服务器...");
                await _syncService.StartAsync();
                Debug.WriteLine("服务器连接成功");

                // 立即加载历史记录
                Debug.WriteLine("开始加载历史记录...");
                UpdateStatus("正在加载历史记录...");
                var history = await _syncService.GetHistoryAsync();
                Debug.WriteLine($"历史记录加载完成，共 {history.Count} 条");

                // 初始化历史记录窗口
                if (_historyWindow == null)
                {
                    Debug.WriteLine("正在创建历史记录窗口...");
                    _historyWindow = new HistoryWindow(_syncService);
                    _historyWindow.UpdateHistory(history);
                    Debug.WriteLine("历史记录窗口已创建并更新");
                }

                // 初始化剪贴板监控
                UpdateStatus("正在初始化剪贴板监控...");
                Debug.WriteLine("开始初始化剪贴板监控...");
                ClipboardMonitor.Start();
                ClipboardMonitor.ContentChanged += OnClipboardChanged;
                Debug.WriteLine("剪贴板监控初始化完成");

                // 更新托盘图标
                if (_notifyIcon != null)
                {
                    _notifyIcon.Icon = new Drawing.Icon(WPFApplication.GetResourceStream(new Uri("pack://application:,,,/Resources/clipboard.ico")).Stream);
                    _notifyIcon.ToolTipText = "剪贴板同步";
                    _notifyIcon.ShowBalloonTip("剪贴板同步", "服务已启动", BalloonIcon.Info);
                }
                
                UpdateStatus("服务已启动");
                Debug.WriteLine("启动完成");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"启动失败: {ex}");
                ShowError($"启动失败: {ex.Message}");
                
                // 更新托盘图标为灰色状态
                if (_notifyIcon != null)
                {
                    _notifyIcon.Icon = GetGrayIcon();
                    _notifyIcon.ToolTipText = "连接失败 - 点击重试";
                    _notifyIcon.DoubleClickCommand = new RelayCommand(async () => await InitializeAsync());
                }
                
                // 不要关闭程序,让用户可以重试
                UpdateStatus("连接失败 - 双击托盘图标重试");
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!_isClosing)
            {
                e.Cancel = true;
                Hide();
            }
            else
            {
                Dispose();
            }
        }

        private async void OnClipboardChanged(object? sender, string content)
        {
            if (!_isSyncEnabled)
            {
                return;
            }

            try
            {
                if (string.IsNullOrEmpty(content))
                {
                    return;
                }

                // 如果未连接,尝试重新连接
                if (!_syncService.IsConnected)
                {
                    try
                    {
                        UpdateStatus("正在重新连接服务器...");
                        await _syncService.StartAsync();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"重新连接失败: {ex}");
                        ShowError("同步失败: 无法连接到服务器");
                        return;
                    }
                }

                await _syncService.UploadContentAsync(content);
                Debug.WriteLine("内容已同步");
                
                if (_historyWindow != null && _historyWindow.IsVisible)
                {
                    await _historyWindow.RefreshHistoryAsync();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"同步失败: {ex}");
                ShowError($"同步失败: {ex.Message}");
                
                // 如果是连接问题,更新托盘图标状态
                if (!_syncService.IsConnected)
                {
                    if (_notifyIcon != null)
                    {
                        _notifyIcon.Icon = GetGrayIcon();
                        _notifyIcon.ToolTipText = "连接失败 - 点击重试";
                        _notifyIcon.DoubleClickCommand = new RelayCommand(async () => await InitializeAsync());
                    }
                    UpdateStatus("连接失败 - 双击托盘图标重试");
                }
            }
        }

        private void ShowHistoryWindow()
        {
            if (_historyWindow == null)
            {
                _historyWindow = new HistoryWindow(_syncService);
            }
            
            if (!_historyWindow.IsVisible)
            {
                _historyWindow.Show();
                _historyWindow.Activate();
            }
            else
            {
                _historyWindow.Activate();
            }
        }

        private void ShowHistoryMenuItem_Click(object sender, RoutedEventArgs e)
        {
            ShowHistoryWindow();
        }

        private void ExitMenuItem_Click(object sender, RoutedEventArgs e)
        {
            _isClosing = true;
            Close();
        }

        private void ShowError(string message)
        {
            Debug.WriteLine($"错误: {message}");
            if (_notifyIcon != null)
            {
                _notifyIcon.ShowBalloonTip("错误", message, BalloonIcon.Error);
            }
            UpdateStatus(message);
        }

        private void UpdateStatus(string status)
        {
            Debug.WriteLine($"状态更新: {status}");
            if (StatusText != null)
            {
                StatusText.Text = status;
            }
        }

        private async void AutoCleanTimer_Tick(object? sender, EventArgs e)
        {
            try
            {
                var now = DateTime.Now;
                if ((now - _lastCleanTime).TotalDays < 1)
                {
                    return;
                }

                var items = await _syncService.GetHistoryAsync();
                var oldItems = items.Where(item => 
                    DateTime.TryParse(item.Time, out var time) && 
                    (now - time).TotalDays > 30).ToList();

                if (oldItems.Any())
                {
                    foreach (var item in oldItems)
                    {
                        await _syncService.DeleteHistoryItemAsync(item.Id);
                    }
                    
                    _notifyIcon?.ShowBalloonTip(
                        "自动清理", 
                        $"已清理 {oldItems.Count} 条过期记录", 
                        BalloonIcon.Info
                    );
                    
                    if (_historyWindow != null && _historyWindow.IsVisible)
                    {
                        await _historyWindow.RefreshHistoryAsync();
                    }
                }

                _lastCleanTime = now;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"自动清理失败: {ex}");
            }
        }

        private void SyncMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            if (menuItem != null)
            {
                _isSyncEnabled = !_isSyncEnabled;
                menuItem.IsChecked = _isSyncEnabled;
                menuItem.Icon = MenuIcons.CreateSyncIcon(_isSyncEnabled);
                
                if (_isSyncEnabled)
                {
                    ClipboardMonitor.Start();
                    _notifyIcon?.ShowBalloonTip("剪贴板同步", "同步已启用", BalloonIcon.Info);
                }
                else
                {
                    ClipboardMonitor.Stop();
                    _notifyIcon?.ShowBalloonTip("剪贴板同步", "同步已暂停", BalloonIcon.Warning);
                }
            }
        }

        private void AutoCleanMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            if (menuItem != null)
            {
                menuItem.IsChecked = !menuItem.IsChecked;
                if (menuItem.IsChecked)
                {
                    _autoCleanTimer.Start();
                    _notifyIcon?.ShowBalloonTip("剪贴板同步", "自动清理已启用", BalloonIcon.Info);
                }
                else
                {
                    _autoCleanTimer.Stop();
                    _notifyIcon?.ShowBalloonTip("剪贴板同步", "自动清理已禁用", BalloonIcon.Warning);
                }
            }
        }

        public void Dispose()
        {
            if (!_isDisposed)
            {
                _isDisposed = true;
                ClipboardMonitor.Stop();
                ClipboardMonitor.ContentChanged -= OnClipboardChanged;
                _autoCleanTimer.Stop();
                _notifyIcon?.Dispose();
                (_syncService as IDisposable)?.Dispose();
            }
        }
    }

    public class RelayCommand : System.Windows.Input.ICommand
    {
        private readonly Action _execute;

        public RelayCommand(Action execute)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
        }

        public event EventHandler? CanExecuteChanged
        {
            add { }
            remove { }
        }

        public bool CanExecute(object? parameter) => true;

        public void Execute(object? parameter)
        {
            _execute();
        }
    }
}